<template>
    <el-dialog
        v-model="dialogVisible"
        @close="closeDialog"
        :title="config.title"
        :close-on-click-modal="false"
        :width="width || '360px'"
    >
        <template #header>
            <p class="f-c">
                <span class="fz18">{{ config.title }}</span>
                <span v-if="!config.hideCondition" class="primary-color fz12 pl15">*按{{ config.condition }}导出</span>
            </p>
        </template>
        <el-form ref="ExportFormRef" :rules="rules" :model="ruleForm" label-width="75px" style="padding: 15px 10px 0">
            <el-form-item label="导出日期" prop="pickerDate">
                <el-date-picker
                    v-model="ruleForm.pickerDate"
                    :editable="false"
                    type="daterange"
                    :format="dateFormat"
                    :value-format="dateFormat"
                    start-placeholder="开始日期"
                    range-separator="-"
                    end-placeholder="结束日期"
                    :disabled-date="disabledDate"
                    class="form-item-value"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="resetForm(ExportFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ExportFormRef)" mr10>确认</el-button>
        </template>
    </el-dialog>

    <el-dialog v-model="routerDownloadCenter" title="温馨提示" width="300px">
        <div class="text-c pt10 pb15">
            <div class="pb8">数据准备中，请前往"下载中心"</div>
            <div>查看任务进度~</div>
        </div>
        <template #footer>
            <el-button @click="onCancel">取消</el-button>
            <el-button type="primary" @click="goNext">立即前往</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
    import { PropType, reactive, ref, watch } from "vue";
    import { useRouter } from "vue-router";
    import { ElMessage } from "element-plus";
    import { _mallStore } from "@/store/config";
    import { postRestV3DownloadStore } from "@/assets/api";

    const router = useRouter();
    const props = defineProps({
        modelValue: {
            type: Boolean,
            default: false,
        },
        config: {
            type: Object as PropType<ObjValueAny>,
            default: () => {
                return {}
            }
        },
        width: {
            type: String,
            default: '',
        },
    });

    const disabledDate = (time: Date) => {
        return (time.getTime() as number) > Date.now();
    }
    const dateFormat = ref<string>('YYYY-MM-DD');
    const ExportFormRef = ref();
    let subStatus: boolean = false;
    let ruleForm = ref<ObjValueAny>({});
    /**
     * 为空时 验证
     * @param message
     */
    const formEmptyRules = (message: string) => {
        return (rule: ObjValueAny, value: string | ObjValueAny, callback: any) => {
            if (subStatus) {
                if (!value || !value.length) {
                    return callback(new Error(message))
                }
            }
            callback()
        }
    }
    // 表单验证 字段
    let rules = reactive<ObjValueAny>({});
    // 表单验证
    const submitForm = async (formEl: any) => {
        subStatus = true;
        if (!formEl) return;
        await formEl.validate((valid: boolean, fields: ObjValueAny) => {
            if (valid) {
                console.log('submit!');
                onSave();
            } else {
                console.log('error submit!', fields);
            }
        });
    }

    // 确认导出
    const onSave = () => {
        const { config }: ObjValueAny = props;
        const pickerDate = JSON.parse(JSON.stringify(ruleForm.value.pickerDate));
        const data: ObjValueAny = {
            name: config.name, // 任务名称
            body: {
                ...config.body
            },
            content: {
                ...config.content
            }
        };
        data.body.start_at = `${pickerDate[0]} 00:00:00`;
        data.body.end_at = `${pickerDate[1]} 23:59:59`;
        exportApi(data);
    }

    // 是否前往 下载中心
    let routerDownloadCenter = ref<boolean>(false);
    const exportApi = (data: ObjValueAny = {}) => {
        if (_mallStore.isGroupManagementPage) {
            data.company_id = _mallStore.companyId;
        } else {
            data.mall_id = _mallStore.mallId;
        }
        cancelDialog();
        routerDownloadCenter.value = true;
        postRestV3DownloadStore(data).then((resp: ObjValueAny) => {
            if (resp.code !== 200) {
                ElMessage.error(resp.msg);
            }
        })
    }
    const onCancel = () => {
        emit('close-router');
        routerDownloadCenter.value = false;
    }
    const goNext = () => {
        router.push('/downloadCenter');
    }
    // 重置表单验证
    const resetForm = (formEl: any) => {
        if (!formEl) return;
        dialogVisible.value = false;
        formEl.resetFields();
    }

    const emit = defineEmits(['update:modelValue', 'close-router']);
    let dialogVisible = ref<boolean>(false);// 显示弹窗
    // 监听 弹窗显示隐藏
    watch(() => props.modelValue, async (newVal: boolean) => {
        dialogVisible.value = newVal;
        handleConfig(props.config);
    });

    const handleConfig = (row: ObjValueAny = {}) => {
        ruleForm.value = {
            pickerDate: row.pickerDate || []
        };
        rules = {
            pickerDate: [{ required: true, validator: formEmptyRules('请选择导出日期'), trigger: 'change' }]
        };
        if (!row.content) {
            row.content = {};
        }
    }
    // 关闭弹窗
    const closeDialog = () => {
        cancelDialog();
        subStatus = false;
        emit('update:modelValue', dialogVisible.value);
    }
    // 取消
    const cancelDialog = () => {
        dialogVisible.value = false;
    }

    defineExpose({
        exportApi,
    })
</script>

<style lang="scss">
    .form-item-value {
        width: 100%;
        max-width: 250px;
    }
</style>